import React from 'react'
// ===================================================================== Temp
import SubmitForm from '#cpt/temp/SubmitForm'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
import Confirm from '#cpt/temp/Confirm'
import TableControls from '#cpt/temp/TableControls'
import Cols from '#private/cols'
// ===================================================================== global declare
const { $fn, $http, $Lazy } = window
// ===================================================================== $Lazy
const Select 		= $Lazy.load(()=>import('@antd/form/select'))
const Page 			= $Lazy.load(()=>import('#tp/page/page-container-scroll'))
const Box 			= $Lazy.load(()=>import('#tp/box/box'))
// 
const message 		= $Lazy.file(()=>import('@antd/message'))
const confirm 		= $Lazy.file(()=>import('@antd/confirm'))
const $cache 		= $Lazy.file(()=>import('#private/cache-api'))
// 
const BatchCode 	= $Lazy.state(()=>import('./cpt/batch-code-table'))
const ImgEdit 		= $Lazy.state(()=>import('../basicInfo-entry/cpt/img-edit'))
const AddDicModal 	= $Lazy.state(()=>import('./cpt/add-dic-modal'))
// ===================================================================== 
const width = '20%'
const proStatus = [ { name: "已审核", value: "1" },{ name: "待审核", value: "0" },{ name: "待保存", value: "-2" }]
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		isMemory: false, 	//是否记忆项目
		isQuickEntry:false, 	// 是否快捷录入
		is_batch: false,	// 是否批量
		specData:{},	// 当前条码信息
		kind_ids: [], // 记忆项目
		key: 0,	//更新图片
		// 搜索表单列表
		formData: [
			{ label: '状态',			name: 'enabled', 			half:true, 		type: 'select',	data:[{name:'待审核',value:'0'},{name:'待录入',value:'-2'}] },
			{ label: '标本箱号',			name: 'box_number', 		half:true, 		type: 'select',  	loading:true, idStr:'name', nameStr:'box_code', },
			{ label: '医院编号/名称',	name: 'hosp_name', 			full:true, 		disabled: true,	p:' '},
			{ label: '加做项目',			name: 'additional_kind', 	width, 			type: 'checkbox', value:0 },
			{ label: '是否复查',			name: 'is_review', 			width, 			type: 'checkbox', value:0 },
			{ label: '是否批量',			name: 'is_batch',			width,			type: 'checkbox',	onValue:({value,formData})=>{
				$fn.hideRows(formData,['start_code', 'end_code'], !value)
				$fn.hideRows(formData,'spec_code', value)
				this.start_code = this.end_code = ''
				this.formRef.reset(['hosp_name', 'additional_kind', 'is_review', 'spec_code', 'remark', 'project_special_request'])
				$fn.disabledRows(formData, 'project_id', true)
				this.setState({formData,data:[],specData:[],is_batch:value})
			}},
			{ label: '是否快捷录入',		name: 'quick_entry_flag',	 	width,			type: 'checkbox', 	onValue:({value})=>{
				this.setState({isQuickEntry:value})
				if(value) document.querySelector('.spec_code .ant-input.ant-input-borderless').focus()
			}},
			{ label: '是否记忆项目',		name: 'memory_project_flag',  	width,		type: 'checkbox', 
				onValue:({value})=>{
					this.setState({isMemory: value})
					this.isMemoryProject(value)
				},
			},
			{ label: '条码号',			name: 'spec_code',  required:true,	full:true,	itemClassName:'spec_code',	autoFocus:true,
				onValue:({value, formData})=>{
					$fn.getRow(formData,'spec_code').btn.disabled = !Boolean(value)
					this.setState({formData})
				},
				btn:{ label:'查询', disabled:true, onClick:value=>{
					const formValue = this.formRef.getValue(['additional_kind'])
					this.specInfo({additional_kind:formValue.additional_kind,spec_code:value})
				} },
				onEnter: (value)=> {
					const formValue = this.formRef.getValue(['additional_kind'])
					this.specInfo({additional_kind:formValue.additional_kind,spec_code:value})
				}
			},
			{ label: '开始条码',			name: 'start_code',  		half:true, hide:true,	required:true,	min:12,	max:14,	itemClassName:'spec_code',
				onValue:({value,formData})=>{
					this.start_code = value
					$fn.getRow(formData,'end_code').btn.disabled = !Boolean(value)
					this.setState({formData})
					if(value.length===12||value.length===14){document.querySelector('.end_code .ant-input.ant-input-borderless').focus()}
				}
			},
			{ label: '结束条码',			name: 'end_code',  			half:true, hide:true,		min:12,	max:14,	itemClassName:'end_code', onValue:({value})=>{
				this.end_code = value
				if(value.length===12||value.length===14){this.generateSpec()}
			},btn:{ label:'生成', disabled:true, onClick:value=>{
				this.generateSpec()
			} }},
			{ label: '选择项目',			name: 'project_id', full:true, 	type: 'select-table',	loading:true, disabled: true, cols:Cols['specimenkindSelect'], isKeydown: 'kind',	onValue:({value})=>{this.addProject(value)}},
			{ label: '备注',			name: 'remark',  	full:true, 		type: 'textarea' },
			{ label: '医院特殊要求',		name: 'project_special_request',  	full:true, 		type: 'textarea',	disabled: true,	p:' ' },
		],
		specType:[]
	}
	query = {}
	model = {}
	submit = {}
	componentDidMount(){
		this.getSelect()
		const { rows, isAudit, view_pic } = $fn.query()
		this.rows = rows
		
		this.model.isAudit = Boolean(+isAudit)
		this.model.view_pic = +view_pic
		
		$fn.hideRows(this.state.formData,'batch', this.model.isAudit)
		
		$fn.fresh.backRefresh()
	}
	
	// 项目数据 表格
	getProjectList = () => {
		const { uuid:spec_id,spec_code } = this.state.specData
		$http.pull(this,'specimen-kind/index', { param: {spec_id,spec_code} })
	}
	
	// 获取下拉数据
	getSelect = () => {
		const { formData } = this.state
		$cache.then( async f => {
			//标本箱号
			$fn.setRow( formData, 'box_number', await f.getCache({ api:'box/select',param:{status:83,limit:1000},way:'post',refresh:true }) )
			// 选择项目
			$fn.setRow( formData, 'project_id', await f.getCache({ api:'specimenkindSelect' }) )
			// 标本类型
			const specType = $fn.setRow( this.cols, 'spec_type', await f.getDicCache({ code: 2000, refresh:true }) )
			
			this.setState({ formData, specType })
		})
	}
	
	// 更新标本类型下拉数据
	refreshDic = () => {
		const { formData } = this.state
		$cache.then( async f => {
			// 标本类型
			const specType = $fn.setRow( this.cols, 'spec_type', await f.getDicCache({ code: 2000, refresh:true }) )
			
			this.setState({ formData, specType })
		})
	}

	// 项目明细
	cols=[
		{ title: '项目代码', 	dataIndex: 'kind_code',				...$fn.table.exp_num,	 },
		{ title: '项目名称', 	dataIndex: 'kind_name', 			width:150 },
		{ title: '项目属性 ', 	dataIndex: 'kind_type_name',  		width:120,  },
		{ title: '项目类别 ', 	dataIndex: 'category_name',  		width:120,  },
		{ title: '子项目 ', 		dataIndex: 'child_kind_name',  		width:150,  },
		{ title: '岗位 ', 		dataIndex: 'project_name',  		width:120,  },
		{ title: '项目状态 ', 	dataIndex: 'enabled',  				width:100,	render: text => $fn.getState(proStatus,text)  },
		{ title: '标本类型 ', 	dataIndex: 'spec_type_name', 		width:150,	name:'spec_type', 	render: (text, {uuid}) => {
			const {specType} = this.state
			return <Select
				name		= 'spec_type'
				value		= {text}  
				data		= {specType}
				width		= '100%'
				outer
				tipTxt		= ' '
				onChange 	= { value  =>{
					confirm.then(f=>{
						const spec_type = value ? specType[value].code : ''
						$http.submit(null,'specimen-kind/savespectype',{ param:{spec_type,uuid}, loadingText:`添加中`}).then(data=>{
							message.then(f=>f.success(`操作成功`))
							this.getProjectList()
						})
					})
				}}
			/>
		}},
		TableControls.controls.call(this,{ width: 150 })
	]	
	// 表格操作按钮
	table_controls = ({uuid,spec_id,enabled}) => {
		const { is_batch } = this.state
		let to_spec_ids = []
		if(is_batch){
			to_spec_ids = this.batchTableRef?.state.data.map(v => v.uuid)
		}
		return [
			TableControls.click.call(this, '添加', ()=>{
				this.addDicModal.open()
			}),
			+enabled !== 1?Confirm.call(this, '删除', 'specimen-kind/del',{
				query:{kind_id:uuid,spec_id:[spec_id],to_spec_ids:is_batch?to_spec_ids:''},
				onOk:()=> {this.getProjectList()}
			}):null,	// 删除
		]
	}	
	
	// 操作按钮
	controls = () => {
		return [
			Controls.back.call(this,{refresh:true, code: 'F1'} ),	// 返回
			Controls.click.call(this, '保存', ()=>{this.saveSpec()},{code: 'F8', hide:this.model.isAudit} ),
			Controls.click.call(this, '审核', ()=>{ this.audit() },{code: 'F10', hide:!this.model.isAudit} ),
			Controls.click.call(this, '保存并审核', ()=>{this.saveAndAudit()},{} ),
			Controls.click.call(this, '下一个 ', ()=>{this.nextSpec()},{code: '—>', hide:this.state.is_batch } ),
		]
	}
	
	// 查询、获取当前条码对应的信息  
	specInfo = ({spec_code, additional_kind}) => {
		const param = this.model.isAudit?{spec_code, additional_kind,audit: 1}:{spec_code, additional_kind}
		$http.submit(null, 'specimen/getspeccodeInfo', { param } ).then(data=>{
			this.setState({specData:data})
			this.formRef.setValue(data)
			if(this.state.isMemory){
				this.addMemoryProject()
			}else{
				$fn.disabledRows(this.state.formData, 'project_id', false)
				this.getProjectList()
			}
		})
	}
	// 生成
	generateSpec = ()=> {
		$http.submit(null,'specimen/checkenter',{ param:{ start_code:this.start_code,end_code:this.end_code }}).then(({info, res})=>{
			if($fn.hasObject(info)){
				$fn.disabledRows(this.state.formData, 'project_id', false)
				this.setState({specData:info})
				this.getProjectList()
				this.formRef.setValue(info)
				this.batchTableRef.setState({data:res})
			}else{
				this.setState({specData:{}})
			}
		}).catch(()=>{
			const specData = {image:''}
			this.setState({specData})
		})
	}
	// 添加项目
	addProject = value => {
		const {uuid,spec_code} = this.state.specData
		$http.submit(null,'specimen-kind/batchadd',{ param:{ kind_ids:[value], spec_id:uuid,spec_code,double_status:0}, loadingText:`添加中`}).then(data=>{
			message.then(f=>f.success(`添加成功`))
			this.getProjectList()
			this.formRef.reset(['project_id'])
			this.state.kind_ids.push(value)
		}).catch(() => {
			// 清空 选择项目
			this.formRef.reset(['project_id'])
		})
	}
	// 保存记忆项目
	isMemoryProject = (value) => {
		let projectData = []
		this.state.data.map(item=>projectData.push(item.kind_id))
		if(value){
			this.setState({kind_ids:projectData })
		}else{
			this.setState({kind_ids:[] })
		}
	}
	// 添加记忆
	addMemoryProject = ()=> {
		const {uuid,spec_code} = this.state.specData
		if(this.state.kind_ids!==[]){
			$http.submit(null,'specimen-kind/batchadd',{ param:{ kind_ids:this.state.kind_ids, spec_id:uuid,spec_code,double_status:0}, loadingText:`添加中`}).then(data=>{
				message.then(f=>f.success(`添加成功`))
				this.getProjectList()
			})
		}
		
	}
	
	// 保存
	saveSpec = ()=> {
		let param
		const { formData } = this.state
		const formValue = this.formRef.getValue([ 'is_review','additional_kind','remark','hosp_name'])
		if(this.state.is_batch){
			let to_codes = []
			this.batchTableRef.state.data.forEach(item=>to_codes.push(item.spec_code))
			param = {spec_id:this.state.specData.uuid,...formValue,to_codes}
		}else{
			param = {spec_id:this.state.specData.uuid,...formValue}
		}
		$http.submit(null,'specimen-kind/savekind',{ param: param, loadingText:`保存中`}).then(data=>{
			message.then(f=>f.success(`保存成功`))
			if (this.state.isQuickEntry){
				this.formRef.reset(['hosp_name', 'additional_kind', 'is_review', 'spec_code','start_code', 'end_code', 'remark', 'project_special_request'])
				this.start_code = this.end_code = ''
				$fn.getRow(formData, 'spec_code').autoFocus = true
				$fn.getRow(formData, 'start_code').autoFocus = true
				this.setState({formData, data:[]})
			}else if(this.state.is_batch){
				this.getProjectList()	// 更新项目表格的 项目状态
			}else{
				this.nextSpec()
			}			
		})
		window.onRefresh = () => {		 /* 保存 添加异步 2021-8-17 --马婷 */
			if (this.state.isQuickEntry){
				this.formRef.reset(['hosp_name', 'additional_kind', 'is_review', 'spec_code','start_code', 'end_code', 'remark', 'project_special_request'])
				this.start_code = this.end_code = ''
				$fn.getRow(formData, 'spec_code').autoFocus = true
				$fn.getRow(formData, 'start_code').autoFocus = true
				this.setState({formData, data:[]})
			}else if(this.state.is_batch){
				this.getProjectList()	// 更新项目表格的 项目状态
			}else{
				this.nextSpec()
			}	
		}
	}
	// 下一个
	nextSpec = ()=> {
		let { key } = this.state
		const formValue = this.formRef.getValue([ 'enabled','box_number'])
		let {enabled, box_number} = formValue
		const { spec_code } = this.state.specData
		if(!enabled){
			this.model.isAudit? enabled = 0 : enabled = -2
		}
		$http.submit(null,'specimen/getnextspeccodeinfo',{ param:{enabled,box_number,spec_code,view_pic:this.model.view_pic}}).then(data=>{
			message.then(f=>f.success(`操作成功`))
			$fn.disabledRows(this.state.formData, 'project_id', false)
			this.setState({specData: data})
			if(this.state.isMemory){
				if(this.state.kind_ids!==[]){
					this.addMemoryProject()
				}
			}else{
				this.getProjectList()	// 更新项目表格的 项目状态
			}
			this.formRef.setValue(data)
		})
		this.setState({key:++key})
	}
	// 保存并审核
	saveAndAudit = ()=> {
		const {uuid} = this.state.specData
		const formValue = this.formRef.getValue([ 'enabled','box_number','additional_kind','is_review','remark'])
		let param = {spec_id:uuid,...this.state.specData,...formValue,status:1}
		if(!this.model.isAudit){
			if(this.state.is_batch){
				let to_codes = []
				this.batchTableRef.state.data.forEach(item=>to_codes.push(item.spec_code))
				param.to_codes = to_codes
			}
		}
		$http.submit(null,'specimen/saveandaudit',{ param:param }).then(data=>{
			message.then(f=>f.success(`保存并审核成功`))
			if(this.state.is_batch){
				this.getProjectList()	// 更新项目表格的 项目状态
			} else{
				this.nextSpec()
			}
		})
		window.onRefresh = () => {		/* 保存并审核 添加异步 2021-8-17 --马婷 */
			if(this.state.is_batch){
				this.getProjectList()	// 更新项目表格的 项目状态
			} else{
				this.nextSpec()
			}	
		}
	}
	
	// 审核
	audit = ()=> {
		const {uuid} = this.state.specData
		const formValue = this.formRef.getValue([ 'enabled','box_number','additional_kind','is_review','remark'])
		let param = {spec_id:uuid,...this.state.specData,...formValue,status:1}
		$http.submit(null,'specimen/audit',{ param:param }).then(data=>{
			this.nextSpec()
		})
	}
		
	
	
	render() {
		const { is_batch, specData, key } = this.state
		return (
			<>
				<Page title={this.model.isAudit?'审核项目':'按条码录入项目'} controls={this.controls()} style={{minHeight: '100%'}} >
					<section className='ex fx pt10 bcf'>
						{/* 左侧表单 */}
						<div className=' ex fv pr10'>
							{ SubmitForm.call(this,{ labelWidth:'s7', onForm:()=>{
								if(this.rows){
									const rows = JSON.parse(decodeURIComponent(this.rows))
									const {spec_code, additional_kind} = rows
									const param = {spec_code, additional_kind}
									this.specInfo(param)
								}
							}} )}
						</div>
						{/* 右侧图片 */}
						<div className='bor1' style={{width:'50%',height:450,marginTop:-15}}> <ImgEdit key={key} src={specData.image} noBg={true}/></div>
					</section>
					{/* 批量条码表格 */}
					{is_batch?
						(<BatchCode onRef={ ref => this.batchTableRef = ref } />):''
					}
					{/* 项目明细表格 */}
					<Box title="项目明细" className='mt5' style={{minHeight:350}} flex contentClassName='rel fv pt10'>
						{ Table.call(this, { wrapClassName: 'xmlr' }) }
					</Box>
				</Page>
				{/* 添加字典 */}
				<AddDicModal onRef = { ref => this.addDicModal = ref } onRefresh = {this.refreshDic} />
			</>
		)
	}
}

export default Index